package com.haixiaoke.saas.enterprise.houseMember.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.auth.ali.service.AliAuthService;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.constant.HouseMemberConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.GsonUtil;
import com.haixiaoke.saas.common.utils.poi.ExcelUtil;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.houseMember.domain.HouseMember;
import com.haixiaoke.saas.houseMember.service.IHouseMemberService;
import com.haixiaoke.saas.order.domain.OrderSnapshoot;
import com.haixiaoke.saas.order.service.IOrderService;
import com.haixiaoke.saas.order.service.IOrderSnapshootService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;


/**
 * 房屋成员Controller
 *
 * @author qixi
 * @date 2024-03-07
 */
@RestController
@RequestMapping("/enterprise/house/member")
public class EnterpriseHouseMemberController extends BaseController {
    @Autowired
    private IHouseMemberService houseMemberService;
    @Autowired
    private IOrderSnapshootService orderSnapshootService;
    @Autowired
    private AliAuthService aliAuthService;
    @Autowired
    private IHouseService houseService;
    @Autowired
    private IUserConsumerService userConsumerService;
    @Autowired
    private IOrderService orderService;

    /**
     * 查询房屋成员列表
     */
    @PreAuthorize("@ss.hasPermi('houseMember:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(HouseMember houseMember) {
        startPage();
        List<HouseMember> list = houseMemberService.selectHouseMemberList(houseMember);
        return getDataTable(list);
    }

    /**
     * 导出房屋成员列表
     */
    @PreAuthorize("@ss.hasPermi('houseMember:member:export')")
    @Log(title = "房屋成员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HouseMember houseMember) {
        List<HouseMember> list = houseMemberService.selectHouseMemberList(houseMember);
        ExcelUtil<HouseMember> util = new ExcelUtil<HouseMember>(HouseMember.class);
        util.exportExcel(response, list, "房屋成员数据");
    }

    /**
     * 获取房屋成员详细信息
     */
    @PreAuthorize("@ss.hasPermi('houseMember:member:query')")
    @GetMapping(value = "/{memberId}")
    public AjaxResult getInfo(@PathVariable("memberId") Long memberId) {
        return success(houseMemberService.selectHouseMemberByMemberId(memberId));
    }

    /**
     * 新增房屋成员
     */
    @PreAuthorize("@ss.hasPermi('houseMember:member:add')")
    @Log(title = "房屋成员", businessType = BusinessType.INSERT)
    @PostMapping
    @TenantScope
    public AjaxResult add(@RequestBody @Valid HouseMember houseMember) {
        String memberPhone = houseMember.getMemberPhone();
        String orderId = houseMember.getOrderId();
        if (StrUtil.isNotEmpty(memberPhone)) {
            if (memberPhone.length() != 11) {
                return error("手机号格式不正确");
            }
            HouseMember member = houseMemberService.selectHouseMemberListByMemberPhone(memberPhone, orderId);
            if (ObjectUtil.isNotEmpty(member)) {
                return error("手机号已存在");
            }
        }
        HouseMember member = houseMemberService.selectHouseMemberListByIdCard(houseMember.getIdCard(), orderId);
        if (ObjectUtil.isNotEmpty(member)) {
            if (!Objects.equals(member.getMemberId(), houseMember.getMemberId())) {
                return error("身份证号已存在");
            }
        }
        House house = houseService.selectHouseById(houseMember.getHouseId());
        if (ObjectUtil.isEmpty(house)) {
            return error("房屋不存在");
        }
        if (houseMemberService.countMemberNumberByOrderId(houseMember.getOrderId()) >= house.getCheckInNumber()) {
            return error("房间已达到入住人数上限");
        }
        Boolean flag = aliAuthService.identityCheck(houseMember.getMemberName(), houseMember.getIdCard());
        if (!flag) {
            return error("姓名或身份证有误，请核对后再试");
        }

        if (orderService.checkReturnOrderByOrderId(orderId)) {
            return error("订单已退租，无法新增");
        }


        houseMember.setMemberType(HouseMember.MEMBER_TYPE_TENEMENT);
        houseMember.setTenantId(TenantContext.getTenantId());
        LoginUser loginUser = getLoginUser();
        houseMember.setDeptId(loginUser.getDeptId());
        houseMember.setCreateBy(loginUser.getUserId().toString());
        return toAjax(houseMemberService.insertHouseMember(houseMember));
    }

    /**
     * 新增房屋成员
     */
    @PreAuthorize("@ss.hasPermi('houseMember:member:add')")
    @Log(title = "房屋成员", businessType = BusinessType.INSERT)
    @PostMapping("/apartment/add")
    @TenantScope
    public AjaxResult apartmentAdd(@RequestBody @Valid HouseMember houseMember) {
        if (StrUtil.isBlank(houseMember.getOrderId()) || StrUtil.isBlank(houseMember.getHouseId())) {
            return error("数据缺失");
        }
        String memberPhone = houseMember.getMemberPhone();
        String orderId = houseMember.getOrderId();
        HouseMember member = houseMemberService.selectHouseMemberListByMemberPhone(memberPhone, orderId);
        if (ObjectUtil.isNotEmpty(member)) {
            return error("手机号已关联本次入住住客");
        }
        HouseMember idCardMember = houseMemberService.selectHouseMemberListByIdCard(houseMember.getIdCard(), orderId);
        if (ObjectUtil.isNotEmpty(idCardMember)) {
            return error("身份证号已存在");
        }
        OrderSnapshoot snapshoot = orderSnapshootService.selectOrderSnapshootByOrderId(houseMember.getOrderId());
        House house = GsonUtil.toBean(snapshoot.getHouseContent(), House.class);
        if (ObjectUtil.isEmpty(house)) {
            return error("房屋不存在");
        }
        if (houseMemberService.countMemberNumberByOrderId(houseMember.getOrderId()) >= house.getCheckInNumber()) {
            return error("人数超过当前房屋限制的数量");
        }
        Boolean flag = aliAuthService.identityCheck(houseMember.getMemberName(), houseMember.getIdCard());
        if (!flag) {
            return error("姓名或身份证有误，请核对后再试");
        }
        houseMember.setTenantId(TenantContext.getTenantId());
        LoginUser loginUser = getLoginUser();
        houseMember.setDeptId(loginUser.getDeptId());
        houseMember.setCreateBy(loginUser.getUsername());
        houseMember.setOperatorId(loginUser.getUserId());
        houseMember.setMemberType(HouseMember.MEMBER_TYPE_TENEMENT);
        return toAjax(houseMemberService.insertHouseMember(houseMember));
    }

    /**
     * 修改房屋成员信息
     */
    @PreAuthorize("@ss.hasPermi('houseMember:member:edit')")
    @Log(title = "房屋成员", businessType = BusinessType.UPDATE)
    @PutMapping
    @TenantScope
    public AjaxResult edit(@RequestBody HouseMember houseMember) {
        HouseMember sqlHouseMember = houseMemberService.selectHouseMemberByMemberId(houseMember.getMemberId());
        if (ObjectUtil.isEmpty(sqlHouseMember)) {
            return error("房屋成员不存在");
        }
        if (HouseMemberConstants.AUTH_STATE_NO.equals(sqlHouseMember.getAuthState())) {
            if (!sqlHouseMember.getAuthState().equals(houseMember.getAuthState())) {
                return error("住客已完成实名认证，请退出后再试");
            }
            Boolean flag = aliAuthService.identityCheck(houseMember.getMemberName(), houseMember.getIdCard());
            if (!flag) {
                return error("姓名或身份证有误，请核对后再试");
            }
        }
        String memberPhone = houseMember.getMemberPhone();
        if (StrUtil.isNotEmpty(houseMember.getMemberPhone())) {
            if (memberPhone.length() != 11) {
                return error("手机号格式不正确");
            }
            HouseMember member = houseMemberService.selectHouseMemberListByMemberPhone(memberPhone, sqlHouseMember.getOrderId());
            if (ObjectUtil.isNotEmpty(member)) {
                if (!Objects.equals(member.getMemberId(), houseMember.getMemberId())) {
                    return error("手机号已存在");
                }
            }
        } else {
            houseMember.setMemberPhone(null);
        }

        HouseMember member = houseMemberService.selectHouseMemberListByIdCard(houseMember.getIdCard(), sqlHouseMember.getOrderId());
        if (ObjectUtil.isNotEmpty(member)) {
            if (!Objects.equals(member.getMemberId(), houseMember.getMemberId())) {
                return error("身份证号已存在");
            }
            if (!StrUtil.equals(houseMember.getMemberName(), member.getMemberName())
                    || !StrUtil.equals(houseMember.getIdCard(), member.getIdCard())) {
                Boolean flag = aliAuthService.identityCheck(houseMember.getMemberName(), houseMember.getIdCard());
                if (!flag) {
                    return error("姓名或身份证有误，请核对后再试");
                }
            }
        }
        LoginUser loginUser = getLoginUser();
        houseMember.setUpdateBy(loginUser.getUserId().toString());
        return toAjax(houseMemberService.updateHouseMember(houseMember));
    }

    /**
     * 修改房屋成员信息
     */
    @PreAuthorize("@ss.hasPermi('houseMember:member:edit')")
    @Log(title = "房屋成员", businessType = BusinessType.UPDATE)
    @PutMapping("/apartment/edit")
    @TenantScope
    public AjaxResult apartmentEdit(@RequestBody HouseMember houseMember) {
        if (StrUtil.isBlank(houseMember.getOrderId()) || StrUtil.isBlank(houseMember.getHouseId())) {
            return error("数据缺失");
        }
        String memberPhone = houseMember.getMemberPhone();
        String orderId = houseMember.getOrderId();
        // OrderSnapshoot snapshoot = orderSnapshootService.selectOrderSnapshootByOrderId(houseMember.getOrderId());
        // HousingAllocation allocation = GsonUtil.toBean(snapshoot.getAllocationContent(), HousingAllocation.class);
        House house = houseService.selectHouseById(houseMember.getHouseId());
        if (ObjectUtil.isEmpty(house)) {
            return error("房屋不存在");
        }
        if (houseMemberService.countMemberNumberByOrderId(houseMember.getOrderId()) > house.getCheckInNumber()) {
            return error("人数超过当前房屋限制的数量");
        }
        HouseMember member = houseMemberService.selectHouseMemberListByMemberPhone(memberPhone, orderId);
        if (ObjectUtil.isNotEmpty(member)) {
            if (!Objects.equals(member.getMemberId(), houseMember.getMemberId())) {
                return error("手机号已关联本次入住住客");
            }
            if (!StrUtil.equals(houseMember.getMemberName(), member.getMemberName())
                    || !StrUtil.equals(houseMember.getIdCard(), member.getIdCard())) {
                Boolean flag = aliAuthService.identityCheck(houseMember.getMemberName(), houseMember.getIdCard());
                if (!flag) {
                    return error("姓名或身份证有误，请核对后再试");
                }
            }
        }
        LoginUser loginUser = getLoginUser();
        houseMember.setUpdateBy(loginUser.getUsername());
        houseMember.setMemberType(HouseMember.MEMBER_TYPE_TENEMENT);
        return toAjax(houseMemberService.updateHouseMember(houseMember));
    }


    /**
     * 修改房管员信息(入住/不入住)
     */
    @PutMapping("/editManager")
    @TenantScope
    public AjaxResult editManager(@RequestBody HouseMember houseMember) {
        LoginUser loginUser = getLoginUser();
        houseMember.setUpdateBy(loginUser.getUserId().toString());
        return toAjax(houseMemberService.editManager(houseMember));
    }

    /**
     * 删除房屋成员
     */
    @PreAuthorize("@ss.hasPermi('houseMember:member:remove')")
    @Log(title = "房屋成员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{memberIds}")
    public AjaxResult remove(@PathVariable Long memberIds) {
        return toAjax(houseMemberService.deleteHouseMemberByMemberId(memberIds));
    }
}
